﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using SharpCmd.IO;
using SharpCmd.Windows.Forms.Progress;

namespace SharpCmd.Dialogs.PanelActions
{
    internal partial class DeleteForm : ProgressForm
    {
        public DeleteForm()
        {
            InitializeComponent();
            this.Icon = MainForm.Instance.Icon;
            this.ProgressBar = progressBarWithText1;
            this.CancelButton = buttonCancel;
            this.PauseButton = buttonPause;
            this.FileNameLabel = labelCurrentFile;
            this.Title = "Delete";
            this.AttachHandlers();
        }

        public List<FSObjectInfo> Infos { get; set; }

        private void DeleteForm_Load(object sender, EventArgs e)
        {
            if (Infos == null)
                throw new InvalidOperationException("DeleteForm: Infos == null!");
        }

        protected override void DoWork(object sender, DoWorkEventArgs e)
        {
            int i = 0;
            foreach (var info in Infos)
            {
                HandlePause();
                if (Worker.CancellationPending)
                    return;
                try
                {
                    if (info.Fake)
                        return;
                    if (info.Type == FSObjectType.Directory)
                    {
                        Directory.Delete(info.FullName);
                    }
                    else if (info.Type == FSObjectType.File)
                    {
                        if ((info.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
                            File.SetAttributes(info.FullName, FileAttributes.Normal);
                        File.Delete(info.FullName);
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    MessageBox.Show("Cannot delete " + info.FullName + " (" + ex.Message + ")");
                }
                ((BackgroundWorker)sender).ReportProgress(0, new ProgressInfo() { CurrentIndex = i++, CurrentItem = info.FullName });
            }
        }

        private void DeleteForm_Shown(object sender, EventArgs e)
        {
            this.labelCurrentFile.Text = "[Preparing to delete...]";
            bwPrepare.RunWorkerAsync();
        }

        #region bwPrepare
        private void bwPrepare_DoWork(object sender, DoWorkEventArgs e)
        {
            Infos = FSObjectInfo.GetAllInfosRecursive(Infos, FSObjectAction.Delete);
        }

        private void bwPrepare_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBarWithText1.Maximum = Infos.Count();
            Worker.RunWorkerAsync();
        }
        #endregion
    }
}